package org.example;

import java.util.ArrayList;

@SuppressWarnings("all")
public class Demo2 {
    private static ArrayList<String> list = new ArrayList();

    public static void main(String[] args) throws Exception {

        new Thread(new Runnable() {
            boolean flag = true;
            String latestEle = null;

            /**
             * 如果变量listSize前加上volatile,myThread1就不会"卡住",System.out.println("进入if了");会执行
             * 如果变量listSize取消volatile,myThread1就会"卡住",System.out.println("进入if了");不会执行
             */
            volatile int listSize;

            public void run() {
                System.out.println("myThread1中的run方法开始执行了");

                while (flag) {

//                    System.out.println("进入while循环了");

                    if (getListSize() != 0) {
                        System.out.println("进入if了");
                        latestEle = list.get(list.size() - 1);
                        try {
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                        System.out.println("获取最后添加的元素是:" + this.latestEle);
                        System.out.println();
                    }
                }
            }

            public int getListSize() {
                listSize = list.size();
                return listSize;
            }

        }, "myThread1").start();


        Thread.sleep(8L);
        list.add("aa");
        list.add("bb");
        System.out.println("主线程执行完成-----打印list:" + list);
    }
}